<template>
  <div class="position-full">
    <div :style="{...styles.track}" class="switch-track position-full" @click="change">
      <div :style="{...styles.panel}" :class="state.values.switch ? 'switch-panel-active' : 'switch-panel-inactive'"
           class="switch-panel"></div>
    </div>
  </div>
</template>

<script>
  import {formatColor} from '@/utils';
  import {mapState} from 'vuex';
  import {WidgetSwitch} from "@/modules/IDE/widget/atom/widgetSwitch";

  export default {
    name: 'SwitchWidget',
    props: {
      widget: {
        type: WidgetSwitch,
        default: () => {
          return {};
        }
      }
    },

    data() {
      return {};
    },
    computed: {
      ...mapState({
        activeTheme: state => state.ide.activeTheme,
      }),
      state() {
        if (!this.widget || !this.widget.UI.state) return;
        return this.widget.getCurrentState();
      },
      styles() {
        const {tempRect = {}} = this.widget;
        const {activeColor = '', inactiveColor = ''} = this.widget.UI.data;
        const {switch: switchVal} = this.state.values;
        const trackStyles = {};
        const panelStyles = {};
        const {height = 0, width = 0} = tempRect;
        if (height) {
          trackStyles.height = `${height}px`;
          panelStyles.width = `${height - 4}px`;
          panelStyles.height = `${height - 4}px`;
          trackStyles.borderRadius = `${height / 2}px`;
        }
        if (switchVal) {
          trackStyles.background = formatColor(activeColor, this.activeTheme);
          panelStyles.right = '2px';
        } else {
          trackStyles.background = formatColor(inactiveColor, this.activeTheme);
          panelStyles.right = `${Math.max(width - height + 2, 2)}px `;
        }
        return {
          track: trackStyles,
          panel: panelStyles
        };
      }
    },
    methods: {
      change() {
        this.state.values.switch = !this.state.values.switch;
      },
    }
  };
</script>

<style scoped lang="less">
  .switch-track {
    transition: background-color 0.3s;
    cursor: pointer;

    .switch-panel {
      position: absolute;
      top: 2px;
      background: @colorWhite;
      border-radius: 50%;
      transition: right 0.3s;
    }
  }
</style>
